package sjsu.android;


import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import dbAdapter.CreateDailyInfoData;
import dbAdapter.DailyAllowance;
import dbAdapter.DailyInfoDBAdapter1;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
public class MonthlyReportActivity extends Activity {
	Date currDate = null;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.chart);
		CreateDailyInfoData data = new CreateDailyInfoData();
		data.create(this);

		Intent intent = getIntent();
		//String dateString= intent.getExtras().getString("Date");
		//String reportType= intent.getExtras().getString("ReportType");
		//Log.v("ReportType", reportType);
		DailyAllowance da = new DailyAllowance();
		final int dailyAllowance = da.getDailyAllowance(this);
		//final int recDailyAllowance = 2000;
		currDate = new java.sql.Date(System.currentTimeMillis());
		ImageButton prevButton = (ImageButton) findViewById(R.id.previousButton);
		prevButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
				int month = currDate.getMonth();
				int year = currDate.getYear();
				if (month == 0 ){

					year = year - 1;
					month = 11;
				}
				else
				{
					month = month - 1;
				}
				currDate = new Date(year, month, 1);

				// TODO Auto-generated method stub
				showReportForDate(dailyAllowance,currDate);

			}
		});
		
		ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton);
	nextButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
				int month = currDate.getMonth();
				int year = currDate.getYear();
				if (month == 11){

					year = year + 1;
					month = 0;
				}
				else
				{
					month = month + 1;
				}
				currDate = new Date(year, month, 1);

				// TODO Auto-generated method stub
				showReportForDate(dailyAllowance,currDate);

			}
		});
		showReportForDate(dailyAllowance, currDate);


	}

	private void showReportForDate(int recDailyAllowance, Date date) {
		TextView monthText = (TextView) findViewById(R.id.MonthDisplayTextView);
		SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
		monthText.setText(sdf.format(date));
		DailyInfoDBAdapter1 db = new DailyInfoDBAdapter1(this);
		db.open();

		HashMap<Integer, Integer> caloriesConsumedMap =(HashMap<Integer, Integer>) db.getCaloriesConsumedForMonth(date.getMonth() + 1, date.getYear() + 1900 );
		HashMap<Integer, Integer> caloriesBurntMap =(HashMap<Integer, Integer>) db.getCaloriesBurntForMonth(date.getMonth() + 1, date.getYear() + 1900);

		int minCaloriesforYaxis = 0;
		int maxCaloriesforYaxis = getMaximumCaloriesforYaxes(caloriesConsumedMap, recDailyAllowance) + 50;
		int numDaysAboveDailyAllowance = getNumberOfDaysAboveDailyAllowance(caloriesConsumedMap, recDailyAllowance);
		int avgCaloriesConsumed = getAvgCaloriesConsumed(caloriesConsumedMap);
		int avgCaloriesBurnt = getAvgCaloriesBurnt(caloriesBurntMap);
		XYSeries data1 = new XYSeries("Calories Consumed");
		for (int day : sort(caloriesConsumedMap.keySet())) {
			data1.add(day, caloriesConsumedMap.get(day));
		}


		XYSeries data2 = new XYSeries("Calories Burnt");
		for (int day : sort(caloriesBurntMap.keySet())) {

			data2.add(day, caloriesBurntMap.get(day));
		}
		XYSeries data3 = new XYSeries("Recommended Daily Allowance");
		for (int i=1;i<=30;i++) {
			data3.add(i, recDailyAllowance);
		}
	
		XYMultipleSeriesDataset xyMultipleSeriesDataset = new XYMultipleSeriesDataset();
		xyMultipleSeriesDataset.addSeries(data1);
		xyMultipleSeriesDataset.addSeries(data2);
		xyMultipleSeriesDataset.addSeries(data3);
		XYMultipleSeriesRenderer xyMultipleSeriesRenderer = new XYMultipleSeriesRenderer();
		xyMultipleSeriesRenderer.setAxesColor(Color.BLACK);
		xyMultipleSeriesRenderer.setLabelsColor(Color.BLACK);
		xyMultipleSeriesRenderer.setLabelsTextSize(12);
		xyMultipleSeriesRenderer.setAxisTitleTextSize(12);
		
		xyMultipleSeriesRenderer.setTextTypeface("sans_serif", Typeface.BOLD);
		xyMultipleSeriesRenderer.setBackgroundColor(Color.rgb(0xf5, 0xf5, 0xf5));
		xyMultipleSeriesRenderer.setApplyBackgroundColor(true);
		//xyMultipleSeriesRenderer.setChartTitle("Monthly Report");
		xyMultipleSeriesRenderer.setXTitle("Days");
		xyMultipleSeriesRenderer.setYTitle("Calories");
		xyMultipleSeriesRenderer.setYAxisMin(minCaloriesforYaxis);
		xyMultipleSeriesRenderer.setYAxisMax(maxCaloriesforYaxis);
		XYSeriesRenderer xySeriesRenderer1 = new XYSeriesRenderer();
		xySeriesRenderer1.setColor(Color.CYAN);
		xySeriesRenderer1.setPointStyle(PointStyle.DIAMOND);
		xyMultipleSeriesRenderer.addSeriesRenderer(xySeriesRenderer1);
		XYSeriesRenderer xySeriesRenderer2= new XYSeriesRenderer();
		xySeriesRenderer2.setColor(Color.RED);
		xySeriesRenderer2.setPointStyle(PointStyle.DIAMOND);
		xyMultipleSeriesRenderer.addSeriesRenderer(xySeriesRenderer2);
		XYSeriesRenderer xySeriesRenderer3 = new XYSeriesRenderer();
		xySeriesRenderer3.setColor(Color.GREEN);
		xySeriesRenderer3.setPointStyle(PointStyle.POINT);
		xyMultipleSeriesRenderer.addSeriesRenderer(xySeriesRenderer3);
		//Intent chartIntent = ChartFactory.getLineChartIntent(this, xyMultipleSeriesDataset, xyMultipleSeriesRenderer);
		//startActivity(chartIntent);
		LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
		layout.removeAllViews();
		GraphicalView mChartView = ChartFactory.getLineChartView(this, xyMultipleSeriesDataset, xyMultipleSeriesRenderer); 
		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		/*
		WebView webView = (WebView) findViewById(R.id.WebView01);
		//String mUrl = "http://chart.apis.google.com/chart?cht=p3&chd=t:30,60,10&chs=250x100&chl=cars|bikes|trucks";
		String mUrl = "http://chart.apis.google.com/";
		webView.loadUrl(mUrl);
		 */
		TextView numTextView = (TextView) findViewById(R.id.valueNumDaysAboveDailyAllowance);
		numTextView.setText( ""+numDaysAboveDailyAllowance);
		
		TextView avgCaloriesConsumedTextView = (TextView) findViewById(R.id.valueAvgCaloriesConsumed);
		avgCaloriesConsumedTextView.setText( ""+avgCaloriesConsumed);
		
		TextView avgCaloriesBurntTextView = (TextView) findViewById(R.id.valueAvgCaloriesBurnt);
		avgCaloriesBurntTextView.setText(""+avgCaloriesBurnt);
		
		TextView oneMonthAgo = (TextView) findViewById(R.id.lastWeekAgoText);
		oneMonthAgo.setText("Last month");
		
		TextView twoMonthsAgo = (TextView) findViewById(R.id.twoWeeksAgoText);
		twoMonthsAgo.setText("2 months ago");
		
		TextView threeMonthsAgo = (TextView) findViewById(R.id.threeWeeksAgoText);
		threeMonthsAgo.setText("3 months ago");
	}

	private int getAvgCaloriesBurnt(HashMap<Integer, Integer> caloriesBurntMap) {
		int total = 0;
		int size = caloriesBurntMap.size();
		int avg = 0;
		for(int calories : caloriesBurntMap.values()){
			total = total + calories;

		}
		if (size != 0){
		avg = total/size;
		}
		return avg;
	}

	private int getAvgCaloriesConsumed(
			HashMap<Integer, Integer> caloriesConsumedMap) {
		int total = 0;
		int size = caloriesConsumedMap.size();
		int avg = 0;
		for(int calories : caloriesConsumedMap.values()){
			total = total + calories;

		}
		if( size != 0)
		{	
		avg = total/size;
		}
		return avg;
		
		
	}

	private int getNumberOfDaysAboveDailyAllowance(
			HashMap<Integer, Integer> caloriesConsumedMap, int recDailyAllowance) {
		int numDaysAboveDailyAllowance = 0;
		for(int calories : caloriesConsumedMap.values()){
			if(calories > recDailyAllowance){
				numDaysAboveDailyAllowance++;
			}

		}
		// TODO Auto-generated method stub
		return numDaysAboveDailyAllowance;
	}

	private List<Integer> sort(Set<Integer> keySet) {
		// TODO Auto-generated method stub
		List<Integer> listSet = new ArrayList<Integer>(keySet);
		Collections.sort(listSet);
		return listSet;
	}

	private int getMaximumCaloriesforYaxes(HashMap<Integer,Integer> caloriesConsumedMap,
			int recDailyAllowance) {
		int maxCaloriesConsumed = Integer.MIN_VALUE;
		for (int calories : caloriesConsumedMap.values()){
			if ( calories > maxCaloriesConsumed)
				maxCaloriesConsumed = calories;

		}
		if (maxCaloriesConsumed > recDailyAllowance)
			return maxCaloriesConsumed;
		else
			return recDailyAllowance;


	}
}